<template>
  <basic-container>
    <!-- START goBack -->
    <div class="el-page-header">
      <div class="el-page-header__left haruyuki-flex-center haruyuki-size-18" @click="goBack" >
        <i class="el-icon-arrow-left"></i>
        <div class="haruyuki-size-16">返回</div>
      </div>
      <div class="el-page-header__content haruyuki-flex-center">
        <el-image
          style="width: 20px; height: 20px"
          src="/img/merchant-icon/posStaff.png"
          fit="fill"
        ></el-image>
        <span class="haruyuki-ml-6">店员管理</span>
        </div>
    </div>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    > 
    
      <template slot-scope="{row}" slot="isOn">
        <span>{{setIsOnName(row.isOn)}}</span>
      </template>
      <template slot-scope="{ row }" slot="staffType">
        <el-tag effect="dark" v-if="row.staffType === 0" style="border:none">{{ row.staffTypeName }}</el-tag>
        <el-tag color="#E6A23C" effect="dark" v-if="row.staffType === 1" style="border:none">{{ row.staffTypeName }}</el-tag>
        <el-tag color="#67C23A" effect="dark" v-if="row.staffType === 2" style="border:none">{{ row.staffTypeName }}</el-tag>
      </template>
      
      <template slot="menuLeft">
        <el-button type="success" icon="el-icon-plus" size="small" @click.stop="handleAdd(2)" >商户管理员</el-button>
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="handleAdd(1)" >门店管理员</el-button>
        <el-button type="warning" icon="el-icon-plus" size="small" @click.stop="handleAdd(0)" >收银员</el-button>
      </template>
      
      <template slot-scope="scope" slot="menu">
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="handleEdit(scope.row)">修 改</el-button>
      </template>
    </avue-crud>
    <!-- 新建 -->
    <el-dialog
      :title="dialogTitle"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      :before-close="handleClose"
    >
      <div>
        <el-form
          label-width="120px"
          :model="form"
          :rules="rules"
          ref="form"
        >
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="姓名:" prop="name">
                  <el-input v-model.trim="form.name" size="small" placeholder="请输入姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系方式:" prop="mobile">
                  <el-input v-model.trim="form.mobile" size="small" placeholder="请输入姓名" @blur="mobileBlur"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="staffType === 0 || staffType === 1">
                <el-form-item label="所属门店:" prop="rpsNo">
                  <el-select
                    size="small"
                    filterable
                    v-model="form.rpsNo"
                    placeholder="请选择所属门店"
                  >
                    <el-option
                      v-for="item in storeColumns"
                      :key="item.rpsNo"
                      :label="item.rpsName"
                      :value="item.rpsNo"
                    >
                      <span style="float: left">{{ item.rpsName }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.rpsNo }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="isShowPwd&&dialogType=='add'">
                <el-form-item label="密码:" prop="password">
                  <el-input v-model.trim="form.password" size="small" placeholder="请输入密码" show-password></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="isShowPwd&&dialogType=='add'">
                <el-form-item label="确认密码:" prop="checkPass">
                  <el-input type="show-password" v-model.trim="form.checkPass" size="small" placeholder="请确认密码" show-password></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8" v-if="dialogType=='edit'">
                <el-form-item label="状态:" prop="isOn">
                  <el-switch
                    :active-value="1"
                    :inactive-value="0"
                    v-model="form.isOn"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="dialogType=='edit'">
                <el-form-item label="退款权限:" prop="isRefundBtn">
                  <el-switch
                    :active-value="1"
                    :inactive-value="0"
                    v-model="form.isRefundBtn"
                  />
                </el-form-item>
              </el-col>
            </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => { dialogVisible = false;initForm()}">取 消</el-button>
        <el-button type="primary" @click="submit" :disabled="btnDisable" >确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import { submitManage, storeList, isStaffPassWord, getList } from "@/api/rb-oem/posinfo/manage";

export default {
  data() {
    return {
      isShowPwd:true,
      staffType:null,
      storeColumns:[],//所属门店
      form: {
					// name: '',
					// mobile: '',
					// password: '',
					// checkPass:'',
					// rpiNo: '',
					// rpsNo: ''//所属门店
      },
      rules: {
				name: {
					type: 'string',
					required: true,
					message: '请输入姓名',
					trigger: ['blur', 'change']
				},
				mobile: [
					{
						required: true,
						message: '请输入联系电话',
						trigger: ['change', 'blur']
					},
					{
						pattern: /^1[0-9]{10}$/,
						message: "手机号格式不正确",
						trigger: ['blur', 'change']
					}
				],
				password: [
					{
						required: true,
						message: '请输入新密码',
						trigger: ['blur', 'change']
					},
					{
						pattern: /^[a-zA-Z0-9]{6,15}$/,
						message: "密码6-15位，由英文、数字组成",
						trigger: ['blur', 'change']
					}
				],
				checkPass: [
					{
						required: true,
						message: '请再次输入新密码',
						trigger: ['blur', 'change']
					},
					{
						pattern: /^[a-zA-Z0-9]{6,15}$/,
						message: "密码6-15位，由英文、数字组成",
						trigger: ['blur', 'change']
					}
				],
				rpsNo: {
					required: true,
					message: '请选择所属门店',
					trigger: ['blur', 'change']
				}
			},
			
      btnDisable:false,
      dialogVisible:false,
      dialogTitle:'',
      dialogType:'',
      query:{},
      data: [],
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel:'序号',
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 100, //搜索框标题宽度
        menuWidth: 100, //操作栏宽度
        emptyBtnText:'重置',
        column: [
          {
            label: "姓名",
            prop: "rpstName",
            search: true,
            type: "input"
          },
          {
            label: "店员类型",
            prop: "staffType",//number 0 收银员 1 门店管理员 2 商户管理员
            search: true,
            type: "select",
            dataType: "number",
            dicUrl: "/api/blade-system/dict/dictionary?code=staff_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
          },
          {
            label: "联系方式",
            prop: "rpstPhone",
            search: true,
            type: "input"
          },
          {
            label: "所属商户",
            prop: "rpiName",
            type: "input"
          },
          {
            label: "所属门店",
            prop: "rpsName",
            type: "input"
          },
          {
            label: "状态",
            prop: "isOn",
            type: "input"
          }
        ]
      }
    };
  },
  computed: {
    setIsOnName() {
      return (val) => {
        if (val === 0) {
          return '禁用';
        } else if (val === 1) {
          return '启用';
        } else {
          return ''
        }
      };
    }
  },
  mounted() {},
  methods: {
    initForm(){
      this.form = {};
      this.isShowPwd = true;
      this.staffType = null;
      this.dialogType = '';
      this.dialogTitle = '';
    },
    /* 渠道信息提交 */
		submit() {
			this.$refs.form.validate().then(res => {
				if(this.isShowPwd){
					if (this.form.password !== this.form.checkPass) {
            this.$message.error("两次密码不一致！");
						return false;
					}
				}
				this.btnDisable = true;
				// this.form.rpiNo = this.query.rpiNo;
				this.form.staffType = this.staffType;
				
        if (this.dialogType === 'add') {
          submitManage(this.form).then(res => {
            this.initForm();

            this.btnDisable = false;
            this.dialogVisible = false;
            this.$message.success("操作成功!");
            this.refreshChange();
          },error =>{
            this.btnDisable = false;
          });
        } else {
          submitManage(this.form).then(res => {
            this.initForm();

            this.btnDisable = false;
            this.dialogVisible = false;
            this.$message.success("修改成功!");
            this.refreshChange();
          },error =>{
            this.btnDisable = false;
          });
        }
      })
      .catch(errors => {
        this.btnDisable = false;
        uni.$u.toast('请检查上面内容');
      });
		},
    /* 输入手机号判断是否输入密码 */
		mobileBlur(){
			isStaffPassWord(this.form.mobile).then(res=>{
				this.isShowPwd = res.data.data;
        if(this.isShowPwd == false){
					this.form.password =='';
					this.form.checkPass =='';
				}
			})
		},
    /* 所属门店 */
		getStoreList(){
			storeList({rpiNo : this.form.rpiNo}).then(res => {
				this.storeColumns = res.data.data
			})
		},
    handleClose(done){
      this.initForm();
      done()
    },
    // 新增
    handleAdd(type){
      this.dialogType='add';
      this.staffType = type;
      this.form.rpiNo = this.$route.query.rpiNo;

      switch(type){
        case 0:
          this.dialogTitle = '新建收银员';
          break
        case 1:
          this.dialogTitle = '新建门店管理';
          this.getStoreList();
          break
        case 2:
          this.dialogTitle = '新建商户管理员';
          this.getStoreList();
          break
      }
      this.dialogVisible = true;
    },
    // 编辑
    handleEdit(row) {
      this.dialogType='edit';
      this.staffType = row.staffType;
      this.form = {
        id: row.id,
        name: row.rpstName,
        mobile: row.rpstPhone,
        password: '',
        checkPass:'',
        rpiNo: row.rpiNo,
        rpsNo: row.rpsNo,//所属门店
        rpsName:row.rpsName,
        staffType:row.staffType,
        isOn: row.isOn,
        isRefundBtn: row.isRefundBtn
      }
      switch(row.staffType){
        case 0:
          this.dialogTitle = '编辑收银员';
          this.getStoreList();
          break
        case 1:
          this.dialogTitle = '编辑门店管理';
          this.getStoreList();
          break
        case 2:
          this.dialogTitle = '编辑商户管理员';
          break
      }
      
        this.dialogVisible = true;
      
      // this.basicDetail(row);
    },
    /**
     * @func 初始化
     * @desc 表格初始化查询数据
     * */
     onLoad(page, params = {}) {
      this.loading = true;
      params.rpiNo = this.$route.query.rpiNo;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
     },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
     currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    /**
     * @func 排序
     * @desc 根据表格字段排序
     * */
     sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    /* 返回页面 */
    goBack() {
      this.$router.$avueRouter.closeTag();
      this.$router.back();
    }
  }
};
</script>

<style lang="scss" scoped>
.el-page-header{
  margin-bottom: 20px;
}
</style>